package com.sxpi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxpi.mapper.RoleMapper;
import com.sxpi.mapper.UserRoleMapper;
import com.sxpi.mapper.UsersMapper;
import com.sxpi.model.entity.Role;
import com.sxpi.model.entity.UserRole;
import com.sxpi.model.entity.Users;
import com.sxpi.model.vo.RoleVo;
import com.sxpi.model.vo.UserRoleVo;
import com.sxpi.service.UserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author happy
 * @create 2024-10-29-{TIME}
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UsersMapper usersMapper;

    @Override
    public UserRoleVo getStore(Long storeId) {
        LambdaQueryWrapper<UserRole> userRoleQuery = new LambdaQueryWrapper<UserRole>().eq(UserRole::getStoreId, storeId);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQuery);

        UserRoleVo userRoleVo = new UserRoleVo();
        List<RoleVo> photographers = new ArrayList<>();
        List<RoleVo> makeupArtists = new ArrayList<>();

        userRoles.forEach(userRole -> {
            LambdaQueryWrapper<Role> roleQuery = new LambdaQueryWrapper<Role>().eq(Role::getId, userRole.getRoleId());
            Role role = roleMapper.selectOne(roleQuery);

            LambdaQueryWrapper<Users> userQuery = new LambdaQueryWrapper<Users>().eq(Users::getId, userRole.getUserId());
            Users user = usersMapper.selectOne(userQuery);

            if (role != null && user != null) {
                RoleVo roleVo = new RoleVo();
                roleVo.setRoleName(role.getRoleName());
                roleVo.setId(user.getId());
                roleVo.setNickname(user.getNickname());
                roleVo.setAvatarUrl(user.getAvatarUrl());
                roleVo.setCount(String.valueOf(userRole.getCount()));

                // 根据 role 的 id 分类
                if (role.getId() == 1) { // 假设 1 是摄影师的 id
                    photographers.add(roleVo);
                } else if (role.getId() == 2) { // 假设 2 是化妆师的 id
                    makeupArtists.add(roleVo);
                }
            }
        });

        // 设置到 UserRoleVo 对象中
        userRoleVo.setPhotographers(photographers);
        userRoleVo.setMakeupArtists(makeupArtists);

        return userRoleVo; // 返回包含 photographers 和 makeupArtists 的 UserRoleVo 对象
    }
}